<template>
  <view v-if="visible" class="modal-overlay" @click="handleOverlayClick">
    <view class="modal-container" @click.stop>
      <view class="modal-header">
        <text class="modal-title">批量创建项目</text>
        <text class="close-btn" @click="$emit('close')">×</text>
      </view>
      
      <view class="modal-content">
        <!-- 指派区县项目经理 -->
        <view class="section">
          <view class="section-title">预指派区县项目经理</view>
          <view v-for="(manager, index) in managers" :key="index" class="manager-item">
            <view class="manager-content">
              <view class="form-row">
                <text class="label">区县:</text>
                <picker 
                  class="district-picker" 
                  :value="manager.districtIndex >= 0 ? manager.districtIndex : 0"
                  :range="districtOptions"
                  @change="(e) => onDistrictChange(e, index)"
                >
                  <view class="picker-view">
                    {{ manager.district || '请选择区县' }}
                  </view>
                </picker>
              </view>
              
              <view class="form-row">
                <text class="label">项目经理:</text>
                <view class="multi-select-container">
                  <view 
                    class="multi-select-trigger" 
                    :class="{ disabled: !manager.district }"
                    @click="!manager.district ? null : toggleManagerSelect(index)"
                  >
                    <text v-if="!manager.selectedManagers || manager.selectedManagers.length === 0">
                      {{ manager.district ? '请选择项目经理' : '请先选择区县' }}
                    </text>
                    <text v-else>
                      已选择 {{ manager.selectedManagers.length }} 个项目经理
                    </text>
                    <text class="arrow">▼</text>
                  </view>
                  
                  <!-- 多选下拉框 -->
                  <view 
                    v-if="manager.showManagerSelect" 
                    class="multi-select-dropdown"
                  >
                    <view 
                      v-for="(managerName, managerIndex) in getManagerOptions(manager.district)"
                      :key="managerIndex"
                      class="multi-select-option"
                      @click="toggleManagerSelection(index, managerName)"
                    >
                      <text class="checkbox" :class="{ checked: isManagerSelected(index, managerName) }">
                        {{ isManagerSelected(index, managerName) ? '☑' : '☐' }}
                      </text>
                      <text class="option-text">{{ managerName }}</text>
                    </view>
                  </view>
                  
                  <!-- 已选择的项目经理标签 -->
                  <view v-if="manager.selectedManagers && manager.selectedManagers.length > 0" class="selected-tags">
                    <view 
                      v-for="selectedManager in manager.selectedManagers" 
                      :key="selectedManager"
                      class="tag"
                    >
                      <text class="tag-text">{{ selectedManager }}</text>
                      <text class="tag-close" @click="removeManagerSelection(index, selectedManager)">×</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            
            <view v-if="managers.length > 1" class="remove-btn" @click="removeManager(index)">
              删除
            </view>
          </view>
          
          <view class="add-btn" @click="addManager">
            + 添加区县指派
          </view>
        </view>
        
        <!-- 上传压缩包 -->
        <view class="section">
          <view class="section-title">上传压缩包</view>
          <view class="upload-area" @click="selectFiles">
            <text class="upload-text">点击选择压缩包文件</text>
            <text class="upload-hint">说明：支持多个文件，文件名必须以"图纸："或"结算："开头\n内容要求：1、结算表需放置在压缩包中"单点结算"目录下。\n2、结算表和图纸的命名方式请按照："子任务编号+站点名称"</text>
          </view>
          
          <!-- 文件列表 -->
          <view v-if="selectedFiles.length > 0" class="file-list">
            <view 
              v-for="(file, index) in selectedFiles" 
              :key="index" 
              class="file-item"
              :class="{ error: !file.isValid }"
            >
              <text class="file-name">{{ file.name }}</text>
              <text class="file-size">{{ formatFileSize(file.size) }}</text>
              <text class="remove-file" @click="removeFile(index)">删除</text>
            </view>
          </view>
          
          <!-- 文件验证错误信息 -->
          <view v-if="fileValidationError" class="error-message">
            {{ fileValidationError }}
          </view>
        </view>
      </view>
      
      <view class="modal-footer">
        <button class="cancel-btn" @click="$emit('close')">取消</button>
        <button 
          class="submit-btn" 
          :disabled="!canSubmit" 
          @click="submitForm"
        >
          创建项目
        </button>
      </view>
    </view>
  </view>
  
  <!-- 历史自检失败模态框 - 放在最外层以确保显示在顶层 -->
  <HistoryCheckFailModal 
    :visible="showHistoryCheckModal"
    :checkData="historyCheckData"
    @close="closeHistoryCheckModal"
  />
</template>

<script>
import HistoryCheckFailModal from './HistoryCheckFailModal.vue'

export default {
  name: 'BatchCreateProjectModal',
  components: {
    HistoryCheckFailModal
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    personsData: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['close', 'success'],
  data() {
    return {
      managers: [
        {
          district: '',
          districtIndex: -1,
          selectedManagers: [],
          showManagerSelect: false
        }
      ],
      selectedFiles: [],
      showHistoryCheckModal: false,
      historyCheckData: {}
    }
  },
  computed: {
    districtOptions() {
      console.log('区县选项:', Object.keys(this.personsData));
      return Object.keys(this.personsData);
    },
    
    fileValidationError() {
      if (this.selectedFiles.length === 0) {
        return '';
      }
      
      const invalidFiles = this.selectedFiles.filter(file => !file.isValid);
      if (invalidFiles.length > 0) {
        return `以下文件名格式不正确：${invalidFiles.map(f => f.name).join(', ')}`;
      }
      
      if (!this.checkFileTypeCompleteness()) {
        return '必须同时上传结算和图纸压缩包才能创建项目';
      }
      
      return '';
    },
    
    canSubmit() {
      // 检查是否有有效的项目经理配置
      const hasValidManagers = this.managers.some(m => 
        m.district && m.selectedManagers && m.selectedManagers.length > 0
      );
      
      // 检查文件
      const hasValidFiles = this.selectedFiles.length > 0 && 
                           this.selectedFiles.every(file => file.isValid) &&
                           this.checkFileTypeCompleteness();
      
      return hasValidManagers && hasValidFiles;
    }
  },
  watch: {
    visible(newVal) {
      if (!newVal) {
        // 当主模态框关闭时，也关闭历史检查模态框
        this.showHistoryCheckModal = false;
        this.historyCheckData = {};
      }
    }
  },
  methods: {
    // 获取指定区县的项目经理选项
    getManagerOptions(district) {
      if (!district || !this.personsData[district]) {
        return [];
      }
      return this.personsData[district];
    },
    
    // 区县选择变化
    onDistrictChange(e, index) {
      const districtIndex = e.detail.value;
      this.managers[index].districtIndex = districtIndex;
      this.managers[index].district = this.districtOptions[districtIndex];
      // 重置项目经理选择
      this.managers[index].selectedManagers = [];
      this.managers[index].showManagerSelect = false;
    },
    
    // 切换项目经理选择框显示
    toggleManagerSelect(index) {
      this.managers[index].showManagerSelect = !this.managers[index].showManagerSelect;
      
      // 关闭其他选择框
      this.managers.forEach((manager, i) => {
        if (i !== index) {
          manager.showManagerSelect = false;
        }
      });
    },
    
    // 切换项目经理选择状态
    toggleManagerSelection(managerIndex, managerName) {
      const manager = this.managers[managerIndex];
      if (!manager.selectedManagers) {
        manager.selectedManagers = [];
      }
      
      const index = manager.selectedManagers.indexOf(managerName);
      if (index > -1) {
        manager.selectedManagers.splice(index, 1);
      } else {
        manager.selectedManagers.push(managerName);
      }
    },
    
    // 检查项目经理是否已选择
    isManagerSelected(managerIndex, managerName) {
      const manager = this.managers[managerIndex];
      return manager.selectedManagers && manager.selectedManagers.includes(managerName);
    },
    
    // 移除项目经理选择
    removeManagerSelection(managerIndex, managerName) {
      const manager = this.managers[managerIndex];
      if (manager.selectedManagers) {
        const index = manager.selectedManagers.indexOf(managerName);
        if (index > -1) {
          manager.selectedManagers.splice(index, 1);
        }
      }
    },
    
    // 添加区县指派
    addManager() {
      this.managers.push({
        district: '',
        districtIndex: -1,
        selectedManagers: [],
        showManagerSelect: false
      });
    },
    
    // 删除区县指派
    removeManager(index) {
      if (this.managers.length > 1) {
        this.managers.splice(index, 1);
      }
    },
    
    // 选择文件
    selectFiles() {
      uni.chooseFile({
        count: 10,
        extension: ['.zip', '.rar', '.7z'],
        success: (res) => {
          const newFiles = res.tempFiles.map(file => ({
            name: file.name,
            size: file.size,
            file: file,
            isValid: this.validateFileName(file.name)
          }));
          this.selectedFiles.push(...newFiles);
        },
        fail: (error) => {
          console.error('选择文件失败:', error);
          uni.showToast({
            title: '选择文件失败',
            icon: 'error'
          });
        }
      });
    },
    
    // 验证文件名
    validateFileName(fileName) {
      return fileName.startsWith('图纸：') || fileName.startsWith('结算：');
    },
    
    // 检查文件类型完整性
    checkFileTypeCompleteness() {
      const hasDrawing = this.selectedFiles.some(file => 
        file.isValid && file.name.startsWith('图纸：')
      );
      const hasSettlement = this.selectedFiles.some(file => 
        file.isValid && file.name.startsWith('结算：')
      );
      return hasDrawing && hasSettlement;
    },
    
    // 删除文件
    removeFile(index) {
      this.selectedFiles.splice(index, 1);
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // 处理遮罩层点击
    handleOverlayClick() {
      // 关闭所有下拉框
      this.managers.forEach(manager => {
        manager.showManagerSelect = false;
      });
    },
    
    // 提交表单 - 支持多文件上传
    async submitForm() {
      const vm = this;
      try {
        uni.showLoading({
          title: '创建中...',
          mask: true
        });

        // 准备指派信息
        const managersData = vm.managers
          .filter(manager => manager.district && manager.selectedManagers && manager.selectedManagers.length > 0)
          .map(manager => ({
            district: manager.district,
            managers: manager.selectedManagers
          }));

        let uploadResult = null;

        // 方案1：使用 files 参数批量上传多个文件
        if (vm.selectedFiles.length > 1) {
          // 准备文件数组
          const files = vm.selectedFiles.map(file => ({
            name: 'files', // 后端接收的字段名
            file: file.file, // 文件对象
            uri: file.file.path // 文件路径
          }));

          uploadResult = await new Promise((resolve, reject) => {
            uni.uploadFile({
              url: './api/creatpss',
              files: files, // 使用 files 参数上传多个文件
              formData: {
                managers: JSON.stringify(managersData),
                totalFiles: vm.selectedFiles.length,
                fileName: JSON.stringify(vm.selectedFiles.map(f => f.name))
              },
              timeout: 1200000,
              header: {
                'Authorization': `Bearer ${uni.getStorageSync("userInfo").token}`
              },
              success: (uploadRes) => {
                // console.log('上传响应:', JSON.stringify(vm.selectedFiles.map(f => f.name)));
                try {
                  let responseData = uploadRes.data;
                  if (typeof responseData === 'string') {
                    responseData = JSON.parse(responseData);
                  }
                  
                  if (uploadRes.statusCode === 200 && responseData.success) {
                    resolve({
                      success: true,
                      data: responseData,
                      message: responseData.message || '上传成功'
                    });
                  } else if (uploadRes.statusCode === 410 && responseData.error === '历史自检失败') {
                    // 处理410历史自检失败错误 - 显示详细模态框
                    console.log('历史自检失败:', responseData);
                    resolve({
                      success: false,
                      isHistoryCheckFail: true,
                      data: responseData,
                      message: responseData.message || responseData.error || '历史自检失败'
                    });
                  } else {
                    reject(new Error(responseData.message || responseData.error || '文件上传失败'));
                  }
                } catch (parseError) {
                  reject(new Error('服务器响应格式错误'));
                }
              },
              fail: (error) => {
                console.error('上传请求失败:', error);
                reject(new Error(`网络请求失败: ${error.errMsg || '未知错误'}`));
              }
            });
          });

          console.log('批量上传成功:', uploadResult);
        } else {
          // 方案2：单文件上传（兼容处理）
          const file = vm.selectedFiles[0];
          uploadResult = await new Promise((resolve, reject) => {
            uni.uploadFile({
              url: './api/creatpss',
              filePath: file.file.path,
              name: 'file',
              formData: {
                fileName: file.name,
                managers: JSON.stringify(managersData),
                totalFiles: 1
              },
              timeout: 1200000,
              header: {
                'Authorization': `Bearer ${uni.getStorageSync("userInfo").token}`
              },
              success: (uploadRes) => {
                try {
                  let responseData = uploadRes.data;
                  if (typeof responseData === 'string') {
                    responseData = JSON.parse(responseData);
                  }
                  
                  if (uploadRes.statusCode === 200 && responseData.success) {
                    resolve({
                      success: true,
                      data: responseData,
                      message: responseData.message || '上传成功'
                    });
                  } else if (uploadRes.statusCode === 410 && responseData.error === '历史自检失败') {
                    // 处理410历史自检失败错误 - 显示详细模态框
                    resolve({
                      success: false,
                      isHistoryCheckFail: true,
                      data: responseData,
                      message: responseData.message || responseData.error || '历史自检失败'
                    });
                  } else {
                    reject(new Error(responseData.message || responseData.error || '文件上传失败'));
                  }
                } catch (parseError) {
                  reject(new Error('服务器响应格式错误'));
                }
              },
              fail: (error) => {
                console.error('上传请求失败:', error);
                reject(new Error(`网络请求失败: ${error.errMsg || '未知错误'}`));
              }
            });
          });

          console.log('单文件上传成功:', uploadResult);
        }

        // 检查是否是历史自检失败
        if (uploadResult.isHistoryCheckFail) {
          // 显示历史自检失败模态框
          vm.historyCheckData = uploadResult.data;
          vm.showHistoryCheckModal = true;
          return; // 不关闭当前模态框，让用户查看详情
        }

        // 显示详细的成功信息
        const successMessage = uploadResult.data?.message || '批量创建成功';
        const createdCount = uploadResult.data?.data?.projects_created || 0;
        const finalMessage = createdCount > 0 ? 
          `${successMessage}，共创建 ${createdCount} 个项目` : 
          successMessage;

        uni.showToast({
          title: finalMessage,
          icon: 'success',
          duration: 3000
        });
        
        vm.resetForm();
        vm.$emit('success', uploadResult.data);
        vm.$emit('close');

      } catch (error) {
        console.error('批量创建项目失败:', error);
        
        // 详细的错误处理和提示
        let errorMessage = '创建失败';
        
        if (error.message) {
          if (error.message.includes('网络')) {
            errorMessage = `网络错误: ${error.message}`;
          } else if (error.message.includes('权限')) {
            errorMessage = `权限错误: ${error.message}`;
          } else if (error.message.includes('文件')) {
            errorMessage = `文件错误: ${error.message}`;
          } else if (error.message.includes('格式')) {
            errorMessage = `数据格式错误: ${error.message}`;
          } else {
            errorMessage = error.message;
          }
        }

        // 显示详细错误信息
        uni.showModal({
          title: '批量创建失败',
          content: errorMessage,
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#007aff'
        });

        // 同时显示简短的toast提示
        uni.showToast({
          title: '创建失败',
          icon: 'error',
          duration: 2000
        });
        
      } finally {
        uni.hideLoading();
      }
    },
    
    // 关闭历史检查失败模态框
    closeHistoryCheckModal() {
      this.showHistoryCheckModal = false;
      this.historyCheckData = {};
    },
    
    // 重置表单
    resetForm() {
      this.managers = [
        {
          district: '',
          districtIndex: -1,
          selectedManagers: [],
          showManagerSelect: false
        }
      ];
      this.selectedFiles = [];
      this.showHistoryCheckModal = false;
      this.historyCheckData = {};
    }
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  overflow: visible;
}

.modal-container {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: visible;
  z-index: 1000;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
}

.manager-item {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.manager-content {
  flex: 1;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.label {
  width: 80px;
  font-size: 14px;
  color: #666;
  margin-right: 12px;
}

.district-picker {
  flex: 1;
  position: relative;
  z-index: 1001;
}

.picker-view {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  background: white;
  color: #333;
  min-height: 20px;
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
  z-index: 1002;
}

.picker-view.disabled {
  background: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

.picker-view::after {
  content: '▼';
  position: absolute;
  right: 8px;
  color: #999;
  font-size: 12px;
}

.multi-select-container {
  flex: 1;
  position: relative;
}

.multi-select-trigger {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  background: white;
  color: #333;
  min-height: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  position: relative;
}

.multi-select-trigger.disabled {
  background: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

.arrow {
  color: #999;
  font-size: 12px;
}

.multi-select-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #ddd;
  border-top: none;
  border-radius: 0 0 4px 4px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1003;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.multi-select-option {
  padding: 8px 12px;
  display: flex;
  align-items: center;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
}

.multi-select-option:hover {
  background: #f5f5f5;
}

.multi-select-option:last-child {
  border-bottom: none;
}

.checkbox {
  margin-right: 8px;
  font-size: 14px;
  color: #666;
}

.checkbox.checked {
  color: #007bff;
}

.option-text {
  font-size: 14px;
  color: #333;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 8px;
}

.tag {
  background: #e3f2fd;
  border: 1px solid #bbdefb;
  border-radius: 4px;
  padding: 4px 8px;
  display: flex;
  align-items: center;
  font-size: 12px;
}

.tag-text {
  color: #1976d2;
  margin-right: 4px;
}

.tag-close {
  color: #1976d2;
  cursor: pointer;
  font-weight: bold;
}

.tag-close:hover {
  color: #d32f2f;
}

.remove-btn {
  background: #ff4757;
  color: white;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  border: none;
  transition: all 0.2s;
  flex-shrink: 0;
  align-self: flex-start;
  margin-top: 4px;
}

.remove-btn:hover {
  background: #ff3742;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(255, 71, 87, 0.3);
}

.add-btn {
  background: #007bff;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
  font-size: 14px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 6px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #007bff;
}

.upload-text {
  display: block;
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #999;
  white-space: pre-line;
}

.file-list {
  margin-top: 16px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 8px;
}

.file-item.error {
  background: #ffebee;
  border-color: #f44336;
}

.file-name {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.file-size {
  font-size: 12px;
  color: #999;
  margin: 0 12px;
}

.remove-file {
  color: #f44336;
  cursor: pointer;
  font-size: 12px;
}

.error-message {
  color: #f44336;
  font-size: 12px;
  margin-top: 8px;
  padding: 8px;
  background: #ffebee;
  border-radius: 4px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #eee;
}

.cancel-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  color: #666;
  cursor: pointer;
}

.submit-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background: #28a745;
  color: white;
  cursor: pointer;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 确保picker下拉选项显示在最顶层 */
:deep(.uni-picker-container) {
  z-index: 1004 !important;
}

:deep(.uni-picker) {
  z-index: 1004 !important;
}
</style>
